import Vue from "vue"
import VueRouter from "vue-router"
import routes from "./routes"
import store from "@/store"
Vue.use(VueRouter);
//重写push和replace
//#region 
let originPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject);
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}
let originReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.apply(this, [location, resolve, reject]);
    } else {
        originReplace.apply(this, [location, () => { }, () => { }])
    }
}
//#endregion
let router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }
})
//路由守卫
router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token
    let name = store.state.user.userInfo.name;
    if (token) {
        //登录了
        if (to.path == "/login") {
            next("/home")
        } else {
            if (!name) {
                try {
                    await store.dispatch("getUserInfo")
                    next()
                } catch (e) {
                    //TOEKN失效了
                    store.dispatch("userLogout")
                    next("/login")
                }
            } else {
                next()
            }
        }
    } else {
        //未登录   不能去trade pay paysuccess center
        let toPath = to.path
        if (toPath.indexOf("/trade") != -1 || toPath.indexOf("/pay") != -1 || toPath.indexOf("/center") != -1) {
            next("/login?topath=" + toPath)
        } else {
            //如果去的不是trade pay paysuccess center 放行
            next()
        }
    }
})
export default router;